package com.huiyin.ui.web;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.bean.BannerBean;
import com.huiyin.constants.Constants;
import com.huiyin.js.JsInterface;
import com.huiyin.js.JsInterface.WebViewClientClickListener2;
import com.huiyin.ui.MainActivity;
import com.huiyin.ui.classic.DianPingShaiDanActivity;
import com.huiyin.ui.classic.ProductsDetailActivity;
import com.huiyin.ui.home.SiteSearchActivity;
import com.huiyin.ui.home.prefecture.ZhuanQuActivity;
import com.huiyin.ui.moments.MomentsDetailActivity;
import com.huiyin.ui.seckill.SeckillActivity;
import com.huiyin.ui.user.LoginActivity;
import com.huiyin.ui.user.MyMessageActivity;
import com.huiyin.utils.AppManager;
import com.huiyin.utils.HandleDataUtil;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.PreferenceUtil;
import com.huiyin.utils.ShareUtils;
import com.huiyin.utils.StringUtils;
import com.huiyin.utils.YsfUtil;
import com.zxing.scan.activity.ZxingCodeActivity;

/**
 * 公共的webview
 * 
 * @author zhyao
 * 
 */
public class CustomWebView extends RelativeLayout implements OnRefreshListener {

	private static final String TAG = "CustomWebView";

	/**
	 * 上下文
	 */
	private Context mContext;

	/**
	 * view
	 */
	private View mView;

	/**
	 * webview
	 */
	private WebView mWebView;

	/**
	 * 下拉刷新
	 */
	private SwipeRefreshLayout mSwipeLayout;

	/**
	 * 加载图片
	 */
	private ImageView mCityLoadingImg;

	/**
	 * 加载图片
	 */
	private ImageView mLoadingImg;

	/**
	 * 加载动画
	 */
	private AnimationDrawable mCityLoadingAnim;

	/**
	 * 加载动画
	 */
	private AnimationDrawable mLoadingAnim;

	/**
	 * Java与JS交互接口
	 */
	private JsInterface jsInterface = new JsInterface();

	/**
	 * 加载url地址
	 */
	private String mLoadUrl;

	/**
	 * 404页面
	 */
	private String mErrorUrl = "file:///android_asset/404.html";

	public CustomWebView(Context context) {
		super(context);

		init(context);
	}

	public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		init(context);
	}

	public CustomWebView(Context context, AttributeSet attrs) {
		super(context, attrs);

		init(context);
	}

	/**
	 * 初始化
	 * 
	 * @param context
	 */
	private void init(Context context) {
		mContext = context;

		mView = LayoutInflater.from(mContext).inflate(R.layout.custom_web_view, null);
		initView();
		initWebView();
		addView(mView);
	}

	public void onResume() {
		mWebView.loadUrl("javascript:onPageShow()");
	}

	public void onStop() {
		mWebView.loadUrl("javascript:onPageHide()");
	}

	/**
	 * UI初始化
	 */
	private void initView() {
		mCityLoadingImg = (ImageView) mView.findViewById(R.id.img_city_loading);
		mCityLoadingImg.setBackgroundResource(R.drawable.swipe_city_loading_animation);
		mCityLoadingAnim = (AnimationDrawable) mCityLoadingImg.getBackground();

		mLoadingImg = (ImageView) mView.findViewById(R.id.img_loading);
		mLoadingImg.setBackgroundResource(R.drawable.swipe_loading_animation);
		mLoadingAnim = (AnimationDrawable) mLoadingImg.getBackground();

		mSwipeLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipe_container);
		mSwipeLayout.setColorScheme(R.color.red, R.color.yellow, R.color.red, R.color.blue_color);
		mSwipeLayout.setOnRefreshListener(this);
	}

	/**
	 * 是否需要下拉刷新页面
	 * 
	 * @param isEnable
	 */
	public void setOnRefreshEnable(boolean isEnable) {
		mSwipeLayout.setEnabled(isEnable);
	}

	/**
	 * 设置404页面是否需要返回按钮，默认有返回按钮
	 * 
	 * @param isNeedBack
	 */
	public void set404Page(boolean isNeedBack) {
		if (isNeedBack) {
			mErrorUrl = "file:///android_asset/404.html";
		} else {
			mErrorUrl = "file:///android_asset/404_noback.html";
		}
	}

	/**
	 * webview设置初始化
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("SetJavaScriptEnabled")
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private void initWebView() {

		mWebView = (WebView) mView.findViewById(R.id.webview_custom);
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setAllowFileAccess(true);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
			webSettings.setAllowFileAccessFromFileURLs(true);
		}
		webSettings.setAllowContentAccess(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setNeedInitialFocus(true);
		webSettings.setDatabaseEnabled(true);
		webSettings.setDomStorageEnabled(true);
		webSettings.setAppCacheEnabled(true);

		// String cacheDirPath = Environment.getExternalStorageDirectory() +
		// "/huiyinlehu/huiyinWebCache";
		// String cacheDirPath =
		// mContext.getFilesDir().getAbsolutePath()+"/huiyinWebCache";
		// Log.d(TAG, "cacheDirPath = " + cacheDirPath);
		String dbPath = mContext.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
		String appCaceDir = mContext.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
		Log.d(TAG, "dbPath = " + dbPath);
		Log.d(TAG, "appCaceDir = " + appCaceDir);

		// 设置数据库缓存路径
		webSettings.setDatabasePath(dbPath);
		// 设置 Application Caches 缓存目录
		webSettings.setAppCachePath(appCaceDir);

		mWebView.addJavascriptInterface(jsInterface, "JSInterface");
		mWebView.setWebViewClient(new MyWebViewClient());
		mWebView.setWebChromeClient(new MyWebChromeClient());
		jsInterface.setWebViewClientClickListener2(new MyWebViewClientClickListener());
	}

	/**
	 * 加载url
	 * 
	 * @param url
	 * @throws Exception
	 */
	public void loadUrl(String url) throws Exception {

		mLoadUrl = url;

		if (StringUtils.isEmpty(mLoadUrl)) {
			throw new Exception("url is null");
		} else if (mWebView == null) {
			throw new Exception("webview is null");
		} else {
			Log.d(TAG, "webview : loadUrl = " + mLoadUrl);
			mWebView.loadUrl(mLoadUrl);
		}
	}

	/**
	 * 开始动画
	 */
	public void startLoadingAnimation() {
		if (mCityLoadingAnim != null) {
			mCityLoadingAnim.start();
		}
		if (mLoadingAnim != null) {
			mLoadingAnim.start();
		}
	}

	/**
	 * 停止动画
	 */
	public void stopLoadingAnimation() {
		if (mCityLoadingAnim != null) {
			mCityLoadingAnim.stop();
		}
		if (mLoadingAnim != null) {
			mLoadingAnim.stop();
		}
	}

	/**
	 * 页面刷新
	 */
	@Override
	public void onRefresh() {
		if (mWebView != null) {
			// mWebView.reload();
			// mWebView.clearCache(true);
			mWebView.loadUrl(mLoadUrl);
		}

	}

	private class MyWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.d(TAG, "shouldOverrideUrlLoading : url = " + url);
			mWebView.loadUrl(url);
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			Log.d(TAG, "onPageStarted : url = " + url);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			Log.d(TAG, "onPageFinished : url = " + url);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			// super.onReceivedError(view, errorCode, description, failingUrl);

			// UIHelper.showToast("网页加载失败");
			// UIHelper.showToast("onReceivedError : errorCode = " + errorCode +
			// " description = " + description + " failingUrl = " + failingUrl);
			Log.d(TAG, "onReceivedError : errorCode = " + errorCode + " description = " + description + " failingUrl = " + failingUrl);
			view.loadUrl(mErrorUrl);
		}
	}

	private class MyWebChromeClient extends WebChromeClient {
		public void onProgressChanged(WebView view, int newProgress) {
			// UIHelper.showToast("newProgress = " + newProgress);
			if (newProgress == 100) {
				mSwipeLayout.setRefreshing(false);
			} else {
				if (!mSwipeLayout.isRefreshing()) {
					mSwipeLayout.setRefreshing(true);
				}
			}

			super.onProgressChanged(view, newProgress);
		};
	}

	private class MyWebViewClientClickListener implements WebViewClientClickListener2 {

		@Override
		public void wvHasClickEnvent(String args) {
			Log.d(TAG, "args : " + args);

			String action = JSONParseUtils.getString(args, "funName");
			String params = JSONParseUtils.getJSONObject(args, "params");

			handleData(action, params);
		}

	}

	/**
	 * 处理js业务
	 * 
	 * @param action
	 *            js方法
	 * @param params
	 *            js参数
	 */
	private void handleData(String action, String params) {
		Intent intent;
		switch (action) {
		// 返回
		case "back_fun":
			AppManager.getAppManager().finishActivity();
			((Activity)mContext).finish();//临时解决项目中没有使用finishActivity的页面，需要多长返回问题
			break;
		// 重新加载页面
		case "reload_web_fun":
			((Activity) mContext).runOnUiThread(new Runnable() {

				public void run() {
					mWebView.loadUrl(mLoadUrl);
				}
			});

			break;
		// 客服
		case "customer_service_fun":
			// 在线客服
			YsfUtil.consultService(mContext, null, null, null);
			break;
		// 分享
		case "share_fun":
			String title = JSONParseUtils.getString(params, "title");
			String url = JSONParseUtils.getString(params, "url");
			String imageUrl = JSONParseUtils.getString(params, "imageUrl");
			String text = JSONParseUtils.getString(params, "text");
			ShareUtils.showShare((Activity) mContext, title, url, imageUrl, text);
			break;
		// 保存客服热线
		case "set_hotline_fun":
			PreferenceUtil.getInstance(mContext).setHotLine(JSONParseUtils.getString(params, "hotline"));
			break;
		// 未登录情况
		case "no_login_fun":
			intent = new Intent(mContext, LoginActivity.class);
			intent.putExtra(LoginActivity.TAG_Action, LoginActivity.Login_To_Finish);
			mContext.startActivity(intent);
			break;
		// 二维码扫描
		case "scan_code_fun":
			mContext.startActivity(new Intent(mContext, ZxingCodeActivity.class));
			break;
		// 消息
		case "message_fun":
			String userId = AppContext.userId;
			if (TextUtils.isEmpty(userId) || null == AppContext.mUserInfo) {
				mContext.startActivity(new Intent(mContext, LoginActivity.class));
			} else {
				mContext.startActivity(new Intent(mContext, MyMessageActivity.class));
			}
			break;
		// 搜索
		case "search_fun":
			intent = new Intent();
			intent.setClass(mContext, SiteSearchActivity.class);
			intent.putExtra("content", "");
			mContext.startActivity(intent);
			AppManager.getAppManager().finishActivity(GoodsListWebActivity.class);
			break;
		// Banner广告
		case "banner_item_fun":
			BannerBean bannerBean = BannerBean.explainJson(params, mContext);
			HandleDataUtil.handleBannerEvent(mContext, bannerBean);
			break;
		// 首页快捷方式
		case "shortcut_fun":
			int fastId = StringUtils.toInt(JSONParseUtils.getString(params, "dID"), -1);
			HandleDataUtil.handShortcut(mContext, fastId);
			break;
		// 秒杀更多
		case "seckill_more_fun":
			intent = new Intent(mContext, SeckillActivity.class);
			mContext.startActivity(intent);
			break;
		// 商品详情
		case "good_detail_fun":
			intent = new Intent(mContext, ProductsDetailActivity.class);
			intent.putExtra(ProductsDetailActivity.BUNDLE_KEY_GOODS_ID, JSONParseUtils.getString(params, "GOODS_ID"));
			intent.putExtra(ProductsDetailActivity.GOODS_NO, JSONParseUtils.getString(params, "GOODS_NO"));
			intent.putExtra(ProductsDetailActivity.STORE_ID, JSONParseUtils.getString(params, "STORE_ID"));
			mContext.startActivity(intent);
			// intent = new Intent(mContext, GoodsDetailWebActivity.class);
			// intent.putExtra(GoodsDetailWebActivity.BUNDLE_KEY_GOODS_ID,
			// JSONParseUtils.getString(params, "GOODS_ID"));
			// intent.putExtra(GoodsDetailWebActivity.BUNDLE_KEY_GOODS_NO,
			// JSONParseUtils.getString(params, "GOODS_NO"));
			// intent.putExtra(GoodsDetailWebActivity.BUNDLE_KEY_STORE_ID,
			// JSONParseUtils.getString(params, "STORE_ID"));
			// mContext.startActivity(intent);
			break;
		// 热点推荐
		case "hot_recommendation_fun":
			intent = new Intent(mContext, ProductsDetailActivity.class);
			intent.putExtra(ProductsDetailActivity.BUNDLE_KEY_GOODS_ID, JSONParseUtils.getString(params, "GOODS_ID"));
			mContext.startActivity(intent);
			break;
		// 促销更多
		case "promotion_more_fun":
			// 活动专题
			intent = new Intent(mContext, ZhuanQuActivity.class);
			intent.putExtra(ZhuanQuActivity.INTENT_KEY_TYPE, Constants.ZhuangQu_Home_Promote);
			intent.putExtra(ZhuanQuActivity.INTENT_KEY_ID, JSONParseUtils.getString(params, "id"));
			intent.putExtra(ZhuanQuActivity.INTENT_KEY_FLAG, 1);
			mContext.startActivity(intent);
			break;
		// 发现详情
		case "show_detail_fun":
			intent = new Intent(mContext, MomentsDetailActivity.class);
			intent.putExtra(MomentsDetailActivity.INTENT_KEY_SHOW_ID, JSONParseUtils.getString(params, "ID"));
			mContext.startActivity(intent);
			break;
		// 立即结算
		case "buy_now_fun":

			break;
		// 晒单评价
		case "goods_comment_fun":
			intent = new Intent(mContext, DianPingShaiDanActivity.class);
			intent.putExtra(DianPingShaiDanActivity.INTENT_KEY_ID, JSONParseUtils.getString(params, "goodsId"));
			mContext.startActivity(intent);
			break;
		// 跳转购物车
		case "shopping_cart_fun":
			AppContext.MAIN_TASK = AppContext.SHOPCAR;
			intent = new Intent(mContext, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			mContext.startActivity(intent);
			AppManager.getAppManager().finishActivity();
			break;
		default:
			break;
		}
	}

}
